<?php

/**
 * Description of ResultToJson
 *
 * @author Robson
 */
class ResultToJson {

    public static function getJsonToResultMysql($title, $stmt) {
        $result = $stmt->get_result();
        $countFields = $result->field_count;
        $fielNames = new ArrayObject();
        $count = $result->num_rows;

        if ($title) {
            $json = '{"' . $title . '":[';
        } else {
            $json = '[';
        }


        $index = 0;
        while ($finfo = $result->fetch_field()) {
            $fielNames[$index++] = $finfo->name;
        }

        $index = 0;
        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
            $json .= '{';
            $indexFields = 0;
            foreach ($fielNames as $name) {
                $json .= '"' . $name . '":';
                if($name == 'conteudo'){
                    $html = base64_encode($row[$name]);
                    $json .= '"' .  $html . '"';
                }else{
                    $json .= '"' . $row[$name] . '"';
                }
                if (($indexFields + 1) < $countFields) {
                    $json .= ',';
                }
                $indexFields++;
            }
            $json .= '}';
            if (($index + 1) < $count) {
                $json .= ',';
            }
            $index++;
        }

        if ($title) {
            $json .= ']}';
        } else {
            $json .= ']';
        }

        $result->close();
        return $json;
    }

}

?>
